﻿using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using BuzzX8.Xmpp.Connectivity;
using BuzzX8.Xmpp.StreamElements;

namespace BuzzX8.Xmpp.Server
{
    public class XmppServer
    {
        private XmppListener listener;

        public XmppServer()
        {
            listener = new XmppListener();
        }

        public void Start()
        {
            listener.Start();
            RunListenerThread();
        }

        private void RunListenerThread()
        {
            ThreadPool.QueueUserWorkItem(listenerThread);
        }

        private void listenerThread(object dummy)
        {
            IXmppChannel channel = listener.AcceptChannel();
            StreamHeader header = ReadResponse<StreamHeader>(channel);

            StreamHeader reasponse = new StreamHeader(StreamType.Client);
            reasponse.To = header.To;
            reasponse.Id = Guid.NewGuid();
            channel.Send(reasponse);

            StreamFeaturesList list = new StreamFeaturesList();
            list.AddFeature(StreamFeatures.StartTls);
            channel.Send(list);

            StreamElement e = channel.Receive();
        }

        private T ReadResponse<T>(IXmppChannel channel) where T : StreamElement
        {
            return (T) channel.Receive();
        }
    }
}
